package com.qf.Utils;/*
 *
 */

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DataSourceUtils {
    private static DruidDataSource dataSource;
    private static ThreadLocal<Connection> threadLocal=new ThreadLocal<>();
    static {
        //读取配置文件
        Properties properties=new Properties();
        InputStream is = DataSourceUtils.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            properties.load(is);
            is.close();
            dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static DataSource getDataSource(){
        return dataSource;
    }
    public static Connection getConnection(){
        Connection conn=threadLocal.get();
        if (conn==null){
            try {
                conn=dataSource.getConnection();
                //绑定线程
                threadLocal.set(conn);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return conn;
    }
    public static void closeAll(Connection conn, Statement stat, ResultSet res){
        try {
            if (stat!=null){
                stat.close();
            }
            if (res!=null){
                res.close();
            }
            if (conn!=null){
                //判断连接是否开启了事务
                if (conn.getAutoCommit()) {
                    threadLocal.remove();//解除绑定
                    conn.close();
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //开启事务
    public static void startAutoCommit() throws Exception{
        Connection conn=threadLocal.get();
        conn.setAutoCommit(false);
    }
    //正常提交
    public static void commit() throws Exception{
        Connection conn=threadLocal.get();
        conn.commit();
    }
    public static void rollback() throws Exception{
        Connection conn=threadLocal.get();
        conn.rollback();
    }
    public static void close() throws Exception{
        Connection conn=threadLocal.get();
        threadLocal.remove();
        conn.close();
    }
}
